package cc.rengu.redp.system.service.impl;

import cc.rengu.redp.system.dao.CommonDictMapper;
import cc.rengu.redp.system.domain.Dict;
import cc.rengu.redp.system.service.CommonDictService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class CommonDictServiceImpl extends ServiceImpl<CommonDictMapper, Dict> implements CommonDictService {

    @Override
    public List<String> getAllFields() {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT FIELD_NAME");
        return this.baseMapper.selectList(queryWrapper)
                .stream()
                .map(Dict::getFieldName)
                .collect(Collectors.toList());
    }

    @Override
    public Map<String, List<String>> loadDictByFields(List<String> dictFields) {
        if (dictFields.size() <= 0) return new HashMap<>();
        LambdaQueryWrapper<Dict> lqw = new LambdaQueryWrapper();
        lqw.in(Dict::getFieldName, dictFields).orderByAsc(Dict::getFieldName);
        List<Dict> dicts = this.list(lqw);
        return  dicts.stream().collect(Collectors.toMap(
                Dict::getFieldName,
                dict -> Lists.newArrayList(dict.getKeyy()),
                (oldList, newList) -> {
                    oldList.addAll(newList);
                    return oldList;
                }));
    }

    @Override
    public Map<String, String> getField(String fieldName) {
        LambdaQueryWrapper<Dict> lqw = new LambdaQueryWrapper();
        lqw.eq(Dict::getFieldName, fieldName);
        List<Dict> dicts = this.list(lqw);
        return dicts.stream().collect(Collectors.toMap(
                Dict::getKeyy,
                Dict::getValuee
        ));
    }
}
